const express = require("express");
const router = express.Router();
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");

dayjs.extend(utc);
dayjs.extend(timezone);

let connectDAO = require("./connect.js");

// 获取公告分页列表
router.get("/get_notices", function (req, res) {
  // 解析参数并设置默认值
  const { page = 1, pageSize = 10 } = req.query;

  // 参数验证
  let pageNum = parseInt(page);
  let pageSizeNum = parseInt(pageSize);
  if (isNaN(pageNum)) pageNum = 1;
  if (isNaN(pageSizeNum)) pageSizeNum = 10;
  const offset = (pageNum - 1) * pageSizeNum;

  // 构建基础SQL
  const dataSql = `SELECT * FROM Notice ORDER BY NoticeID DESC LIMIT ${pageSizeNum} OFFSET ${offset}`;
  const countSql = `SELECT COUNT(*) AS total FROM Notice`;

  // 先查询总数
  connectDAO.queryDataBySQL(countSql, (countResult) => {

    const total = countResult[0].total;

    // 再查询分页数据
    connectDAO.queryDataBySQL(dataSql, (dataResult) => {
      res.send({
        code: 200,
        msg: "获取成功",
        data: {
          records: dataResult,
          pagination: {
            current: pageNum,
            pageSize: pageSizeNum,
            total: total
          }
        }
      });
    });
  });
});

// 新增公告
router.post("/add_notice", function (req, res) {
  const { Content } = req.body;
  const sql = `INSERT INTO Notice (Content) VALUES ('${Content}')`;
  connectDAO
    .queryDataBySQL(sql)
    .then(() => {
      res.send({ code: 200, msg: "Success" });
    })
});


// 更新公告
router.put("/update_notice", function (req, res) {
  const { Content, NoticeID } = req.body;
  const sql = `UPDATE Notice SET Content = '${Content}' WHERE NoticeID = ${NoticeID}`;
  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.affectedRows > 0) {
      res.send({
        code: 200,
        msg: "Success",
      });
    } else {
      res.send({
        code: 200,
        msg: "no data",
      });
    }
  })
});

// 删除公告
router.delete("/delete_notice/:NoticeID", function (req, res) {
  const { NoticeID } = req.params;
  const sql = `DELETE FROM Notice WHERE NoticeID = ${NoticeID}`;
  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.affectedRows > 0) {
      res.send({
        code: 200,
        msg: "Success"
      })
    }
  })
});

module.exports = router;
